package com.ruirenyun.util.common;


import com.ruirenyun.entity.constant.SYS;
import com.ruirenyun.util.exception.CommonException;
import com.ruirenyun.util.redis.utils.RedisUtil;

import java.io.Serializable;
import java.security.SecureRandom;
import java.util.Date;

/*
 * Created with IntelliJ IDEA.
 *
 * @author Deng Ye
 * @date  2020/9/22
 * @description  验证码类
 * @modifiedBy
 * @version: 1.0
 */

public class ValidCode implements Serializable {
    private static final long serialVersionUID = 9004237132303923384L;
    private static int expire = 3 * 60 * 1000;//过期时间
    private static int limitTime = 60 * 1000;//限制发送间隔时间
    private String randCode;
    private Date createTime;

    public static void setValidCode(String phone, String code) {
        ValidCode validCode = new ValidCode();
        validCode.setCreateTime(new Date());
        validCode.setRandCode(code);
        RedisUtil redisUtil = BeanUtil.getBean(RedisUtil.class);
        redisUtil.set(phone, validCode, 300);
    }

    public static ValidCode getValidCode(String phone) {
        RedisUtil redisUtil = BeanUtil.getBean(RedisUtil.class);
        return (ValidCode) redisUtil.get(phone);
    }

    /**
     * 验证码是否正确
     *
     * @return
     */
    public static boolean isCorrectValidCode(String key, String code) {
        ValidCode validCode = getValidCode(key);
        Date nowDate = new Date();
        long nowt = nowDate.getTime();
        if (validCode != null) {
            long old = validCode.getCreateTime().getTime();
            if (nowt - old <= expire) {
                if (validCode.getRandCode().equals(code)) {
                    RedisUtil redisUtil = BeanUtil.getBean(RedisUtil.class);
                    redisUtil.del(key);
                    return true;
                } else {
                    throw new CommonException(SYS.SMS002.name());
                }
            } else {
                throw new CommonException(SYS.SMS003.name());
            }
        }
        return false;
    }

    /**
     * 验证码是否正确
     *
     * @return
     */
    public static boolean validCodeLimit(String phone) {
        ValidCode validCode = getValidCode(phone);
        Date nowDate = new Date();
        long nowt = nowDate.getTime();
        if (validCode != null) {
            long old = validCode.getCreateTime().getTime();
            return nowt - old >= limitTime;
        } else {
            return true;
        }
    }

    public static String getRandomCode() {
        return "" + (new SecureRandom().nextInt(899999) + 100000);
    }

    public String getRandCode() {
        return randCode;
    }

    public void setRandCode(String randcode) {
        this.randCode = randcode;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}
